package com.sky.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.constant.StatusConstant;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.entity.DishFlavor;
import com.sky.entity.SetmealDish;
import com.sky.exception.DeletionNotAllowedException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DishServiceImpl implements DishService {
    @Autowired
    private DishMapper dishMapper;
    @Autowired
    private DishFlavorMapper dishFlavorMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private SetmealDishMapper setmealDishMapper;

    @Override
    public PageResult list(DishPageQueryDTO dishPageQueryDTO) {
        PageHelper.startPage(dishPageQueryDTO.getPage(), dishPageQueryDTO.getPageSize());
        QueryWrapper<Dish> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(dishPageQueryDTO.getCategoryId() != null, "category_id", dishPageQueryDTO.getCategoryId())
                .like(StringUtils.hasLength(dishPageQueryDTO.getName()), "name", dishPageQueryDTO.getName())
                .eq(dishPageQueryDTO.getStatus() != null, "status", dishPageQueryDTO.getStatus())
                .orderByDesc("update_time");
        List<Dish> dishes = dishMapper.selectList(queryWrapper);
        Page<Dish> dishPage = (Page<Dish>) dishes;
        List<DishVO> dishVOList = dishPage.stream().map(dish -> {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(dish, dishVO);
            dishVO.setCategoryName(categoryMapper.selectById(dish.getCategoryId()).getName());
            return dishVO;
        }).collect(Collectors.toList());

        return new PageResult(dishPage.getTotal(), dishVOList);
    }

    @Override
    public List<DishVO> listDishVOByCategoryId(Long categoryId) {
        return dishMapper.selectList(new QueryWrapper<Dish>()
                .eq("category_id", categoryId)
                .eq("status", StatusConstant.ENABLE)
                .orderByDesc("update_time")).stream().map(dish -> {
            DishVO dishVO = new DishVO();
            BeanUtils.copyProperties(dish, dishVO);
            dishVO.setCategoryName(categoryMapper.selectById(dish.getCategoryId()).getName());
            return dishVO;
        }).collect(Collectors.toList());
    }

    @Override
    public DishVO getById(Long id) {
        Dish dish = dishMapper.selectById(id);
        DishVO dishVO = new DishVO();
        BeanUtils.copyProperties(dish, dishVO);
        dishVO.setCategoryName(categoryMapper.selectById(dish.getCategoryId()).getName());
        dishVO.setFlavors(dishFlavorMapper.selectList(
                new QueryWrapper<DishFlavor>().eq("dish_id", dish.getId()))
        );
        return dishVO;
    }

    @Override
    public List<Dish> listDishByCategoryId(Long categoryId) {
        return dishMapper.selectList(new QueryWrapper<Dish>()
                .eq("category_id", categoryId)
                .orderByDesc("update_time")
        );
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void insert(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.insert(dish);

        Long dishId = dish.getId();
        List<DishFlavor> dishFlavors = dishDTO.getFlavors();
        if (!CollectionUtils.isEmpty(dishFlavors)) {
            dishFlavors.forEach(flavor -> flavor.setDishId(dishId));
            dishFlavorMapper.insert(dishFlavors);
        }
    }

    @Override
    @Transactional
    public void update(DishDTO dishDTO) {
        Dish dish = new Dish();
        BeanUtils.copyProperties(dishDTO, dish);
        dishMapper.updateById(dish);

        Long dishId = dish.getId();
        dishFlavorMapper.delete(new QueryWrapper<DishFlavor>().eq("dish_id", dishId));

        List<DishFlavor> dishFlavors = dishDTO.getFlavors();
        if (!CollectionUtils.isEmpty(dishFlavors)) {
            dishFlavors.forEach(flavor -> flavor.setDishId(dishId));
            dishFlavorMapper.insert(dishFlavors);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delete(List<Long> ids) {
        List<Dish> dishes = dishMapper.selectByIds(ids);
        if (!CollectionUtils.isEmpty(dishes)) {
            dishes.forEach(dish -> {
                if(StatusConstant.ENABLE.equals(dish.getStatus())) {
                    throw new DeletionNotAllowedException(MessageConstant.DISH_ON_SALE);
                }
            });

            if (setmealDishMapper.exists(new QueryWrapper<SetmealDish>().in("dish_id", ids))) {
                throw new DeletionNotAllowedException(MessageConstant.DISH_BE_RELATED_BY_SETMEAL);
            }

            dishFlavorMapper.delete(new QueryWrapper<DishFlavor>().in("dish_id", ids));
            dishMapper.deleteByIds(ids);
        }
    }

    @Override
    public void updateStatus(Integer status, Long id) {
        Dish dish = Dish.builder()
                .id(id)
                .status(status)
                .build();
        dishMapper.updateById(dish);
    }
}
